package netty.serializable.objectdecoderandencoder.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class OrderClient {
	
	public void connect(String host,int port){
		NioEventLoopGroup workGroup = new NioEventLoopGroup();
		
		Bootstrap client = new Bootstrap();
		
		client.group(workGroup).option(ChannelOption.TCP_NODELAY, true)
		.channel(NioSocketChannel.class)
		.handler(new ChannelInitializer<Channel>() {

			@Override
			protected void initChannel(Channel ch) throws Exception {
				ch.pipeline().addLast(new ObjectDecoder(1024*1024, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
				ch.pipeline().addLast(new ObjectEncoder());
				ch.pipeline().addLast(new OrderClientHandler());
			}
		});
		
		ChannelFuture f;
		try {
			f = client.connect(host, port).sync();
			f.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			workGroup.shutdownGracefully();
		}
		
	}
	
	public static void main(String []args){
		new OrderClient().connect("127.0.0.1", 8080);
	}
}
